package de.karlNet.sambamanager.ldapController.commands.attributeBuilder;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapModel.dns.LdapDNSARecord;
@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ARecordBuilder {
	public BasicAttributes buildARecordAttributesWithDC(LdapDNSARecord ldapDNSARecord) {
		BasicAttributes basicAttributes = new BasicAttributes();
		for (BasicAttribute attribute : this.buildARecordAttributeListWithDC(
				ldapDNSARecord)) {
			basicAttributes.put(attribute);
		}
		return basicAttributes;
	}

	public List<BasicAttribute> buildARecordAttributeListWithDC(LdapDNSARecord ldapDNSARecord) {
		List<BasicAttribute> attributes = this.buildARecordAttributeList(ldapDNSARecord);
		BasicAttribute samaccountname = new BasicAttribute("dc",
				ldapDNSARecord.getCn());
		attributes.add(samaccountname);
		return attributes;
	}
	
	public List<BasicAttribute> buildARecordAttributeList(
			LdapDNSARecord ldapDNSARecord) {
		ArrayList<BasicAttribute> attributes = new ArrayList<BasicAttribute>();
	

		BasicAttribute objectClass = new BasicAttribute("objectclass");
		objectClass.add("dnsNode");
		attributes.add(objectClass);

		BasicAttribute dnsRecord = new BasicAttribute("dnsRecord");
		dnsRecord.add(this.createRawData(ldapDNSARecord));
		attributes.add(dnsRecord);

		return attributes;
	}
	
	public byte[] createRawData(LdapDNSARecord ldapDNSARecord) {
		String[] ipTokens = ldapDNSARecord.getIpAddress().split("\\.");
		
		ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt(ldapDNSARecord.getTtl());
        byte[] ttlArray = buffer.array();
        
        int[] ipRaw = new int[4];
		for (int i = 0; i < ipRaw.length; i++) {
			ipRaw[i] = Integer.parseInt(ipTokens[i]);
		}
		int[] dnsRecordRawInt = { 
				4, 
				0, 
				1, 
				0x00, 
				0x05,
				0xf0, 
				0x00, 
				0x00,
				0x01, 
				0x00, 
				0x00, 
				0x00, 
				ttlArray[0] & 0xFF, 
				ttlArray[1] & 0xFF, 
				ttlArray[2] & 0xFF, 
				ttlArray[3] & 0xFF, 
				0x00,
				0x00, 
				0x00, 
				0x00, 
				0x00, 
				0x00, 
				0x00, 
				0x00, 
				ipRaw[0], ipRaw[1],	ipRaw[2], ipRaw[3] };
		byte[] dnsRecordRaw = new byte[dnsRecordRawInt.length];
		for (int i = 0; i < dnsRecordRaw.length; i++) {
			dnsRecordRaw[i] = (byte)(dnsRecordRawInt[i]);
		}
		return dnsRecordRaw;
	}
}
